package com.xgpro.common.controller;
import com.xgpro.common.enums.ResultCodeEnum;
import com.xgpro.common.exceptions.BusinessRuntimeException;
import com.xgpro.common.results.ResponseResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 全局的异常处理
 */
@RestControllerAdvice
public class GlobalControllerAdvice {

    private static Logger logger = LoggerFactory.getLogger(GlobalControllerAdvice.class);

    /**
     * 拦截捕捉自定义异常
     * @param bex
     * @return
     */
    @ExceptionHandler(BusinessRuntimeException.class)
    @ResponseBody
    public ResponseResult busErrorHandler(BusinessRuntimeException bex){
        logger.error("catch exception : {}\r\nexception: ",bex.getMessage(),bex);
        return ResponseResult.failure(bex.getErrorCode(),bex.getMessage());
    }

    /**
     * 全局异常处理
     * @param ex
     * @return
     */
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public ResponseResult errorHandler(Exception ex){
        logger.error("catch Exception : {}\r\nexception:",ex.getMessage(),ex);
        return ResponseResult.failure(ResultCodeEnum.ERROR.getCode(),ResultCodeEnum.ERROR.getMessage());
    }
}
